今天將對 NumPy
的運算做簡單講解,涵蓋基本的運算功能和範例:
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result_add = arr1 + arr2
print(result_add) # 輸出: [5 7 9]
result_sub = arr1 - arr2
print(result_sub) # 輸出: [-3 -3 -3]
result_mul = arr1 * arr2
print(result_mul) # 輸出: [ 4 10 18]
result_div = arr1 / arr2
print(result_div) # 輸出: [0.25 0.4 0.5 ]
sqrt_arr = np.sqrt(arr1)
print(sqrt_arr) # 輸出: [1. 1.41421356 1.73205081]
exp_arr = np.exp(arr1)
print(exp_arr) # 輸出: [ 2.71828183 7.3890561 20.08553692]
log_arr = np.log(arr1)
print(log_arr) # 輸出: [0. 0.69314718 1.09861229]
可以使用 np.dot()
進行矩陣的內積計算:
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result_dot = np.dot(matrix1, matrix2)
print(result_dot)
輸出:
[[19 22]
[43 50]]
transposed_matrix = np.transpose(matrix1)
print(transposed_matrix)
輸出:
[[1 3]
[2 4]]
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# 矩陣乘法
result = np.dot(arr1, arr2)
print(result)
輸出:
[[19 22]
[43 50]]